package com.feng.spring.hibernate.extend.core;

import com.feng.spring.hibernate.extend.core.sql.ParameterSQL;
import com.feng.spring.hibernate.extend.core.sql.PlaceholderSQL;
import com.feng.spring.hibernate.extend.core.sql.SQL;
import com.feng.spring.hibernate.extend.core.sql.StaticSQL;

import java.util.List;
import java.util.Map;

public class DefaultHibernateExtendSQLBuilder implements HibernateExtendSQLBuilder{

    /**
     * 解析成sql和相关查询参数
     *
     * @param sqlList       sql相关语句
     * @param paramValueMap 原始查询参数
     * @param queryParams   目标查询参数
     */
    public String buildSQL(List<SQL> sqlList, Map<String, Object> paramValueMap, List<Object> queryParams) {
        StringBuilder sqlBuilder = new StringBuilder();
        for (SQL sql : sqlList) {
            if (sql instanceof StaticSQL) {
                sqlBuilder.append(((StaticSQL) sql).getSql());
                continue;
            }
            if (sql instanceof ParameterSQL) {
                Object o = paramValueMap.get(((ParameterSQL) sql).getName());
                Object[] objs = null;
                if (o != null) {
                    if (o.getClass().getTypeName().startsWith("[")) {
                        objs = (Object[]) o;
                    } else if (o instanceof java.util.List) {
                        List list = (List) o;
                        objs = list.toArray();
                    }
                }
                if (objs != null) {
                    StringBuilder paramsSB = new StringBuilder();
                    for (Object obj : objs) {
                        paramsSB.append("?,");
                        queryParams.add(obj);
                    }
                    if (paramsSB.length() > 0) {
                        paramsSB.deleteCharAt(paramsSB.length() - 1);
                    }
                    sqlBuilder.append(paramsSB);
                } else {
                    sqlBuilder.append('?');
                    queryParams.add(o);
                }
                continue;
            }
            if (sql instanceof PlaceholderSQL) {
                sqlBuilder.append(paramValueMap.get(((PlaceholderSQL) sql).getName()));
            }
        }

        return sqlBuilder.toString();
    }
}
